<template>
  <div class="employees-container">
    <pageTools>
      <template #left>
        <el-tag>共{{ total }}条记录</el-tag>
      </template>
      <template #right>
        <el-button
          v-arrowBtn="'q3'"
          size="mini"
          type="danger"
          @click="handleDownload"
        >excel导出</el-button>
        <el-button
          size="mini"
          type="success"
          @click="$router.push('/import?type=user')"
        >excel导入</el-button>
        <el-button
          size="mini"
          type="primary"
          @click="addEmp"
        >新增员工</el-button>
      </template>
    </pageTools>

    <!-- 表格 -->
    <el-card>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="username" label="姓名" />
        <el-table-column label="头像" align="center">
          <template slot-scope="scoped">
            <img
              v-imgError="defaultImg"
              style="width: 40px"
              :src="scoped.row.staffPhoto"
              alt=""
            >
          </template>
        </el-table-column>
        <el-table-column sortable prop="mobile" label="手机号" />
        <el-table-column sortable prop="workNumber" label="工号" />
        <el-table-column sortable label="聘用形式">
          <!-- <template> 未知 </template> -->
          <template slot-scope="scoped">
            {{ formatEmployment(scoped.row.formOfEmployment) }}
          </template>
        </el-table-column>
        <el-table-column sortable prop="departmentName" label="部门" />
        <el-table-column sortable prop="correctionTime" label="入职时间" />
        <!-- <el-table-column sortable prop="formOfEmployment" label="状态">
          <template>
            <el-switch
              v-model="value"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </template>
        </el-table-column> -->
        <el-table-column sortable label="操作" width="250">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="handleClick(scope.row)"
            >查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button
              type="text"
              size="small"
              @click="roleHandle(scope.row.id)"
            >角色</el-button>
            <el-button type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 对话框 -->
    <el-dialog title="添加员工" :visible.sync="dialogFormVisible">
      <emDia v-if="dialogFormVisible" @success="success" />
    </el-dialog>

    <!-- 分页 -->
    <div style="margin: 20px; text-align: right">
      <el-pagination
        :current-page="currentPage4"
        :page-sizes="[20, 40, 60, 80]"
        :page-size="pageObj.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="dialogRoleVisible">
      <setRole
        v-if="dialogRoleVisible"
        ref="setRole"
        @success="dialogRoleVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeList } from '@/api/employees'
import defaultImg from '@/assets/common/img.jpeg'
import EmployeeEnum from '@/constant/employees'
import emDia from './empDia.vue'
import setRole from './setRole.vue'
export default {
  name: '',
  components: {
    emDia,
    // emDia:()=>import('./empDia.vue'),
    setRole
  },
  data() {
    return {
      value: true,
      tableData: [],
      defaultImg,
      currentPage4: 1,
      pageObj: {
        page: 1,
        size: 20
      },
      total: 0,
      dialogFormVisible: false,
      tHeader: [],
      dialogRoleVisible: false
    }
  },
  computed: {},
  created() {
    this.loadEmp()
  },
  methods: {
    handleClick(row) {
      // console.log(row)
      // 实现页面跳转
      /*
      声明式导航: router-link
      编程式导航: this.$router.push()
      */
      // this.$router.push('/employees/detail/'+row.id) === path:'detail/:id'
      // this.$router.push('/detail/'+row.id)  //path:'/detail/:id'
      // this.$router.push({ path: '/detail/' + row.id })  // path: '/detail/:id',
      // this.$route.push({name:'detail',params:{id:row.id}})  /* name: 'detail', // 给路由规则加一个name path: '/detail/:id', */
      // this.$router.push({
      //   name: 'detail',
      //   query: { id: row.id },
      //   params: { name: 'jack' }
      // })  /* name: 'detail', // 给路由规则加一个name path: '/detail/:name', */
      // this.$router.push({
      //   name: 'detail',
      //   params: { id:row.id },
      //   query:{
      //     name:'jack',
      //     id:row.id
      //   }
      // })
      this.$router.push({ name: 'detail', params: { id: row.id }})
    },
    async loadEmp() {
      const res = await getEmployeeList(this.pageObj)
      this.tableData = res.data.rows
      // console.log(this.tableData, 666777)
      this.total = res.data.total
    },
    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageObj.size = val
      this.loadEmp()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageObj.page = val
      this.loadEmp()
    },
    formatEmployment(num) {
      // num = num || 1
      var obj = EmployeeEnum.hireType.find((item) => item.id == num)
      // EmployeeEnum.hireType.forEach((item) => {
      //   console.log(item.id)
      // })

      // return obj.value
      return obj ? obj.value : '未知'

      // console.log(obj.value, 9988)
    },

    addEmp() {
      this.dialogFormVisible = true
    },
    success() {
      // 添加员工成功后
      this.dialogFormVisible = false
      // 刷新页面
      this.loadEmp()
    },
    // 导出
    async handleDownload() {
      const res = await getEmployeeList({ paeg: 1, size: this.total })
      import('@/vendor/Export2Excel').then((excel) => {
        // 定义表头
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const tHeader =this.tHeader
        // 需要导出的数据
        // const list = this.tableData
        const list = res.data.rows // 处理所有的数据
        const data = this.formatJson(list) // 返回值需要是一个二维数组
        console.log(data, 900)
        // const data = [
        //   ['1', 'web', 'java', 'python', 'php'],
        //   ['2', 'web2', 'java2', 'python2', 'php2']
        // ]  // 返回值需要是一个二维数组
        console.log(data, list, 1122)
        excel.export_json_to_excel({
          // multiHeader: ['姓名', '年龄', '性别', '爱好', '', '', '', '', '', ''], // 二维数组 设置多表头
          // merges: ['A1:A2', 'B1:D1'], // 合并
          header: this.tHeader, // 表头
          data, // 显示表格数据
          filename: 'web70', // 设置导出的文件名
          autoWidth: true, // 自动匹配表格宽度
          bookType: 'xlsx' // 设置文件导出的类型 文件后缀
        })
      })
    },
    formatJson(jsonData) {
      const map = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      this.tHeader = Object.values(map)
      console.log(this.tHeader, 6655)
      // jsonData：表格数据
      console.log(jsonData, 1100)
      // 处理数据的===把英文转换成中文, 还有时间需要转换,并且需要返回一个二维数组
      return jsonData.map((item) => {
        // 获取的每一项的数据有很多,我们需要做筛选
        var newObj = {} // 需要收集的字段数据
        var enKey = Object.keys(map) // 获取的是英文键[]
        enKey.forEach((key) => {
          // 会循环10次
          newObj[map[key]] = item[key]
        })
        console.log(newObj, 771)
        return Object.values(newObj) // 获取的是收集对象中的值存在一个数组中
        //  ['1063705989926227968', 'c8b7722b1139bb9b346409e503302e82', '13800000002', '管理员', '2018-11-02T08:00:00.000+0000', 1, '2018-11-30T00:00:00.000+0000', '9002']
      })
    },
    // 分配角色
    roleHandle(id) {
      /*
     步骤分析:
     1-点击角色按钮
     2-显示对话框
     3-获取所有的角色
     4-获取当前用户拥有的角色并选中
     5-点击确认按钮
       5-1封装api
       5-2调用
       5-3发送请求
       5-4成功后,关闭对话框
     */
      this.dialogRoleVisible = true
      this.$nextTick(() => {
        this.$refs.setRole.id = id
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.employees-container {
  padding: 20px;
}
</style>
